package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User login(UserLoginDTO dto) {
        //1,根据前端传过来的code授权码去访问微信的接口换取openid
        HashMap<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",dto.getCode());
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        //2,判断openid是否为空,如果为空,则表示登录失败
        if(null == openid){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //3,判断当前的微信用户是否是新用户,如果不是,则需要添加到user表中(注册)
        User user = userMapper.getUserByOpenId(openid);
        if(null == user){
            //是新用户,需要新增,重新构建一个user对象
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.save(user);
        }

        return user;
    }
}
